package concurrency.exclusion_mutuelle.v_synchronized;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ExclusionMutuelleLock {

	private long varPartagee;
	private Lock pv = new ReentrantLock();
	
	public ExclusionMutuelleLock() {
		varPartagee = 0;
	}
	
	public void incremente() {
		pv.lock();
		try {
			// Debut SC
			varPartagee++;
			// Fin SC
		} finally {
			pv.unlock();
			description();
		}
	}
	
	public void decremente() {
		pv.lock();
		try {
			// Debut SC
			varPartagee--;
			description();
			//Fin SC
		} finally {
			pv.unlock();
		}
	}
	
	private void description() {
		String des = Thread.currentThread().getName() + " VAR : " + varPartagee;
		System.out.println(des);
	}
	
	private class Processus extends Thread {
		
		private int repetition;
		private boolean incrementeOp;
		
		public Processus(String id, int repetition, boolean incrementeOp) {
			setName(id);
			this.repetition = repetition;
			this.incrementeOp = incrementeOp;
		}
		
		@Override
		public void run() {
			for (int i = 0; i < repetition; i++) {
				if (incrementeOp) {
					incremente();
				} else {
					decremente();
				}
				Thread.yield();
			}
		}
	}
	
	public static void main(String[] args) {
		ExclusionMutuelleLock ex = new ExclusionMutuelleLock();
		Processus p1 = ex.new Processus("Thread_1", 100, true);
		Processus p2 = ex.new Processus("Thread_2", 100, false);
		p1.start();
		p2.start();
		
	}
}
